<template>
    <!-- 查询和操作区域 -->
    <div class="page-header">
        <div class="search-toolbar" v-permission="'sys:user:read'">
            <el-input v-model="keyword" @keyup.enter="init" style="width: 200px;margin-right:5px;"
                placeholder="账号/名称/手机号" clearable />
            <el-button type="primary" @click="init">查询</el-button>
        </div>
        <div class="toolbar">
            <el-button v-permission="'sys:user:read'" type="info" @click="init">刷新</el-button>
            <el-button v-permission="'sys:user:create'" type="primary" @click="handleCreate">新增</el-button>
            <el-button v-permission="'sys:user:delete'" type="danger" @click="handleDeleteBatch">批量删除</el-button>
        </div>
    </div>
    <!-- 表格区域 -->
    <div class="page-main">
        <el-table :data="tableData" style="width: 100%" stripe max-height="calc(100vh - 190px)"
            @selection-change="handleSelectionChange">
            <el-table-column align="center" type="selection" width="40" />
            <el-table-column align="center" fixed prop="account" label="账号" width="120" />
            <el-table-column align="center" fixed prop="userName" label="名称" width="100" />
            <el-table-column align="center" prop="nickName" label="昵称" width="120" />
            <el-table-column align="center" label="性别" width="60">
                <template #default="{ row }">
                    {{ row.sex === 'M' ? '男' : (row.sex === 'F' ? '女' : '') }}
                </template>
            </el-table-column>
            <el-table-column align="center" label="头像" width="80">
                <template #default="{ row }">
                    <el-image :src="row.avatar" fit="fill" />
                </template>
            </el-table-column>
            <el-table-column align="center" prop="phone" label="手机号" width="120" />
            <el-table-column align="center" prop="mail" label="邮箱" width="200" />
            <el-table-column align="center" prop="address" label="通讯地址" width="200" />
            <el-table-column align="center" label="账号锁定" width="100">
                <template #default="{ row }">
                    <el-tag effect="light" :type="row.locked ? 'info' : 'success'" disable-transitions>
                        {{ row.locked ? '锁定' : '正常' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" label="账号状态" width="100">
                <template #default="{ row }">
                    <el-tag effect="light" :type="row.disabled ? 'info' : 'success'" disable-transitions>
                        {{ row.disabled ? '禁用' : '启用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" width="200">
                <template #default="{ row }">
                    {{ row.createTime && format(row.createTime, 'yyyy-MM-dd HH:mm:ss') }}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="updateTime" label="更新时间" width="200">
                <template #default="{ row }">
                    {{ row.updateTime && format(row.updateTime, 'yyyy-MM-dd HH:mm:ss') }}
                </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" min-width="250">
                <template #default="{ row }">
                    <el-button v-permission="'sys:user:update'" type="success" size="small"
                        @click="handleUpdate(row)">编辑</el-button>
                    <el-button v-permission="'sys:user:role'" type="warning" size="small"
                        @click="handleGrantRole">角色</el-button>
                    <el-button v-permission="'sys:user:delete'" type="danger" size="small"
                        @click="handleDelete(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 分页区域 -->
    <div class="page-footer">
        <el-pagination v-model:current-page="current" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50]"
            size="small" layout="total, sizes, prev, pager, next, jumper," :total="total" @size-change="init"
            @current-change="init" />
    </div>
    <!-- 新增和编辑窗口 -->
    <el-drawer v-model="drawerVisible" direction="rtl" class="demo-drawer" size="30%" :close-on-click-modal="false" :show-close="false" :close-on-press-escape="false">
        <template #header>
            <h4>{{ formData.id ? '编辑数据' : '新增数据' }}</h4>
        </template>
        <template #default>
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="auto" center>
                <el-form-item label="账号" prop="account">
                    <el-input v-model="formData.account" :disabled="formData.id ? true : false" />
                </el-form-item>
                <el-form-item label="名称" prop="userName">
                    <el-input v-model="formData.userName" />
                </el-form-item>
                <el-form-item label="昵称" prop="nickName">
                    <el-input v-model="formData.nickName" />
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="formData.sex">
                        <el-radio value="M">男</el-radio>
                        <el-radio value="F">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="头像" prop="avatar">
                    <el-upload class="avatar-uploader" action="" :show-file-list="false" list-type="picture"
                        :http-request="handleUpload">
                        <img v-if="formData.avatar" :src="formData.avatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model.number="formData.phone" />
                </el-form-item>
                <el-form-item label="邮箱" prop="mail">
                    <el-input v-model="formData.mail" />
                </el-form-item>
                <el-form-item label="通讯地址" prop="address">
                    <el-input v-model="formData.address" />
                </el-form-item>
                <el-form-item label="排序" prop="orderId">
                    <el-input v-model.number="formData.orderId" />
                </el-form-item>
                <el-form-item label="账号锁定" prop="locked">
                    <el-switch v-model="formData.locked" :active-value="1" :inactive-value="0" />
                </el-form-item>
                <el-form-item label="账号禁用" prop="disabled">
                    <el-switch v-model="formData.disabled" :active-value="1" :inactive-value="0" />
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
            <div style="flex: auto">
                <el-button @click="cancelClick">取消</el-button>
                <el-button type="primary" @click="confirmClick">保存</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup>
import { get, post, del, postFile } from '@/utils/request'
import { onMounted, reactive, ref } from 'vue'
import { format } from 'date-fns'

//表格数据
const tableData = ref([])
//当前页码
const current = ref(1)
//每页显示数据
const pageSize = ref(10)
//表格总数
const total = ref(0)
//表格标签
const formRef = ref(null)
//多选数据
const selectedRows = ref([])
//新增、编辑弹窗
const drawerVisible = ref(false)
//查询关键字
const keyword = ref('')
//提交数据对象
const formData = ref({
    id: '',
    account: '',
    userName: '',
    nickName: '',
    avatar: '',
    sex: 'M',
    phone: '',
    mail: '',
    address: '',
    orderId: 0,
    locked: 0,
    disabled: 0,
})

//表单校验规则
const formRules = reactive({
    account: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    userName: [
        { required: true, message: '请输入名称', trigger: 'blur' }
    ],
    phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    mail: [
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ]
})

//页面挂在完毕，执行初始化方法
onMounted(() => {
    init()
})

//页面初始化方案
const init = async () => {
    const loadingInstance = ElLoading.service({
        target: document.querySelector('.page-main'),
        fullscreen: false,
        lock: true,
        text: '加载中......'
    })
    const res = await get('sysUser/getSysUserList', {
        'size': pageSize.value,
        'current': current.value,
        'keyword': keyword.value
    })
    loadingInstance.close()
    tableData.value = res.data.list
    total.value = res.data.total
}

//新增弹窗
const handleCreate = () => {
    drawerVisible.value = true
    formData.value = {
        sex: 'M'
    }
}

//保存数据
const confirmClick = async () => {
    await formRef.value.validate(async (valid) => {
        if (valid) {
            const url = formData.value.id ? 'sysUser/updateSysUserById' : 'sysUser/createSysUser'
            await post(url, formData.value)
            ElMessage.success('保存成功')
            drawerVisible.value = false
            init()
        }
    })
}

//新增或编辑窗口取消保存
const cancelClick = () => {
    drawerVisible.value = false
    formRef.value.resetFields()
}

//编辑弹窗
const handleUpdate = (row) => {
    drawerVisible.value = true
    formData.value = JSON.parse(JSON.stringify(row))
}

//多选操作
const handleSelectionChange = (rows) => {
    selectedRows.value = rows
}

//删除数据
const handleDelete = async (ids) => {
    try {
        await ElMessageBox.confirm('确认删除选中的数据吗？', '提示', {
            type: 'warning'
        })
        await del('sysUser/deleteSysUserByIds', { ids })
        ElMessage.success('删除成功')
        init()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '删除失败')
        }
    }
}

//批量删除数据
const handleDeleteBatch = async () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的数据')
        return
    }
    const ids = selectedRows.value.map(row => row.id).join(',')
    handleDelete(ids)
}

//角色授权弹窗
const handleGrantRole = async (row) => {

}

//图片上传
const handleUpload = async (file) => {
    let res = await postFile('/upload', ({ file: file.file }))
    ElMessage.success('上传成功！');
    console.info(res.data)
    formData.value.avatar = res.data;
}

</script>

<style lang="less" scoped>
.page-header {
    height: 50px;
    display: flex;
    justify-content: space-between;
}

.page-footer {
    height: 50px;
    display: flex;
    justify-content: flex-end;
}

.avatar-uploader .avatar {
    width: 120px;
    height: 120px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
}
</style>